package com.lottery.ruok.lottrey.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.ChargeAdapter;
import com.lottery.ruok.lottrey.adapter.fragmentManager.ChargeFragmentManager;
import com.lottery.ruok.lottrey.eventbusObject.ChargePush;
import com.lottery.ruok.lottrey.eventbusObject.ChargeSuccess;
import com.lottery.ruok.lottrey.eventbusObject.GetAccountWithPush;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetPayTypeRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetPayTypeResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.ui.ShapeIndicatorView;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.SystemUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import ui.NavigateBar;
import utils.CashierInputFilter;
/*
 * 充值
 * */

public class ChargeActivity extends BaseActivity implements View.OnClickListener {
    public final static String ANALYTIC_VERSION = "1.0";


    @BindView(R.id.money50)
    TextView money50;
    @BindView(R.id.money100)
    TextView money100;
    @BindView(R.id.money500)
    TextView money500;
    @BindView(R.id.money1000)
    TextView money1000;
    @BindView(R.id.money2000)
    TextView money2000;
    @BindView(R.id.money5000)
    TextView money5000;
    @BindView(R.id.money9999)
    TextView money9999;
    @BindView(R.id.edit_costorm_money)
    EditText money;
    @BindView(R.id.navigateBar)
    NavigateBar navigateBar;
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;
    @BindView(R.id.custom_indicator)
    ShapeIndicatorView customIndicator;
    @BindView(R.id.tabs)
    TabLayout tabLayout;
    @BindView(R.id.vp_view)
    ViewPager vpView;
    @BindView(R.id.balance)
    TextView balance;

    public List<GetPayTypeResponse> data;
    private GetProfileResponse getProfileResponse;
    private ChargeAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_charge);
        ButterKnife.bind(this);
        initData();
        initView();
        load();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(GetAccountWithPush getAccountWithPush) {
        updateView();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ChargePush event) {
        finish();
    }
    /**
     * 更新View
     */
    private void updateView() {
        tv_user_name.setText("用户名:" + UserInfo.getUsername());
        balance.setText("余额:" + UserInfo.getAccount() + "元");
    }

    private void load() {
        loadData();
    }

    private void initData() {

    }

    private void setChoose(TextView textView, boolean choose) {
        if (choose) {
            textView.setTextColor(getResources().getColor(R.color.purples));
            textView.setBackgroundResource(R.drawable.bg_corners_32);
        } else {
            textView.setTextColor(Color.parseColor("#5b5b5b"));
            textView.setBackgroundResource(R.drawable.bg_corners_31);
        }
    }

    private void allChooseFalse() {
        setChoose(money50, false);
        setChoose(money100, false);
        setChoose(money500, false);
        setChoose(money1000, false);
        setChoose(money2000, false);
        setChoose(money5000, false);
        setChoose(money9999, false);
    }

    @Override
    public void onClick(View view) {
        allChooseFalse();

        switch (view.getId()) {
            case R.id.money50:
                money.setText(money50.getContentDescription());
                money.setSelection(money.getText().length());

                setChoose(money50, true);
                break;
            case R.id.money100:
                money.setText(money100.getContentDescription());
                money.setSelection(money.getText().length());

                setChoose(money100, true);
                break;
            case R.id.money500:
                money.setText(money500.getContentDescription());
                money.setSelection(money.getText().length());

                setChoose(money500, true);
                break;
            case R.id.money1000:
                money.setText(money1000.getContentDescription());
                money.setSelection(money.getText().length());

                setChoose(money1000, true);
                break;
            case R.id.money2000:
                money.setText(money2000.getContentDescription());
                money.setSelection(money.getText().length());

                setChoose(money2000, true);
                break;
            case R.id.money5000:
                money.setText(money5000.getContentDescription());
                money.setSelection(money.getText().length());

                setChoose(money5000, true);
                break;
            case R.id.money9999:
                money.setText(money9999.getContentDescription());
                money.setSelection(money.getText().length());

                setChoose(money9999, true);
                break;
        }
    }


    @Override
    protected void onDestroy() {
        ChargeFragmentManager.clear();
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleMessage(ChargeSuccess chargeSuccess) {
        finish();
    }

    private void initView() {
//        InputFilter[] inputFilters = {new CashierInputFilter()};
//        money.setFilters(inputFilters);

        money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                saveTwoPoint(charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                allChooseFalse();
                switch (editable.toString()) {
                    case "50":
                        setChoose(money50, true);
                        break;
                    case "100":
                        setChoose(money100, true);
                        break;
                    case "500":
                        setChoose(money500, true);
                        break;
                    case "1000":
                        setChoose(money1000, true);
                        break;
                    case "2000":
                        setChoose(money2000, true);
                        break;
                    case "5000":
                        setChoose(money5000, true);
                        break;
                    case "9999":
                        setChoose(money9999, true);
                        break;
                }

                ChargeFragmentManager.setMoney(money.getEditableText().toString().trim());
            }
        });


        money50.setOnClickListener(this);
        money100.setOnClickListener(this);
        money500.setOnClickListener(this);
        money1000.setOnClickListener(this);
        money2000.setOnClickListener(this);
        money5000.setOnClickListener(this);
        money9999.setOnClickListener(this);

        vpView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                removeSoftKeyboard(view);
                return false;
            }
        });

        getBalance();
        navigateBar.setOnIconClickListener(new NavigateBar.OnIconClickListener() {
            @Override
            public void OnIconClick(View view) {
                //  SystemUtil.hiddenInputForce(ChargeActivity.this);
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                finish();
            }
        });
    }

    private void saveTwoPoint(CharSequence s) {
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                money.setText(s);
                money.setSelection(s.length());
            }
        }
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            money.setText(s);
            money.setSelection(2);
        }

        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                money.setText(s.subSequence(0, 1));
                money.setSelection(1);
                return;
            }
        }
    }

    private void getBalance() {
        updateAccount(new AfterUpdateAccount() {
            @Override
            public void afterUpdateAccount(GetProfileResponse g) {
                getProfileResponse = g;
                UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                updateView();
            }
        });
    }

    /**
     * 加载数据
     */
    private void loadData() {
        RetrofitBase.getRetrofit().create(GetPayTypeRequest.class).getResult(UserInfo.getToken())
                .compose(RxHelper.<ArrayList<GetPayTypeResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<GetPayTypeResponse>>(this) {
                    @Override
                    protected void _onNext(ArrayList<GetPayTypeResponse> g) {
                        data = g;
                        initViewPage();
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }

    private void initViewPage() {

        if (mAdapter == null) {
            mAdapter = new ChargeAdapter(getSupportFragmentManager(), data);//给ViewPager设置适配器
            vpView.setAdapter(mAdapter);
        }
        if (data.size() > 0) {
            vpView.setOffscreenPageLimit(data.size());
        }
        tabLayout.setTabsFromPagerAdapter(mAdapter);
        tabLayout.getTabAt(0).select();

        if (data.size() == 1) {
            customIndicator.setVisibility(View.GONE);
        } else {
            customIndicator.setVisibility(View.VISIBLE);
        }
        customIndicator.setupWithTabLayout(tabLayout);
        customIndicator.setupWithViewPager(vpView);
    }
}
